package com.atguigu.yygh.order.service.impl;

import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.mapper.RefundInfoMapper;
import com.atguigu.yygh.order.service.RefundInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/4/2 1:47
 */
@Service
public class RefundInfoServiceImpl implements RefundInfoService {
    @Autowired
    private RefundInfoMapper refundInfoMapper;
    @Override
    public RefundInfo findByOrderId(Long orderId) {
        QueryWrapper<RefundInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        return refundInfoMapper.selectOne(queryWrapper);

    }

    @Override
    public RefundInfo saveRefundInfo(PaymentInfo paymentInfo) {

        //先查询退款记录是否存在
        QueryWrapper<RefundInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", paymentInfo.getOrderId());
        RefundInfo refundInfo = refundInfoMapper.selectOne(queryWrapper);
        if (refundInfo != null) return refundInfo;
        //不存在则新增退款记录
        refundInfo = new RefundInfo();
        refundInfo.setSubject("没时间去医院，退款");
        refundInfo.setCreateTime(new Date());
        refundInfo.setOrderId(paymentInfo.getOrderId());
        refundInfo.setPaymentType(PaymentTypeEnum.WEIXIN.getStatus());
        refundInfo.setOutTradeNo(paymentInfo.getOutTradeNo());
        refundInfo.setRefundStatus(RefundStatusEnum.UNREFUND.getStatus());
        refundInfo.setTotalAmount(paymentInfo.getTotalAmount());
        refundInfoMapper.insert(refundInfo);
        return refundInfo;
    }

    @Override
    public void updateById(RefundInfo refundInfo) {
        refundInfoMapper.updateById(refundInfo);
    }
}
